"""
@summary: Uses samtools to perform a batch index of bam files
@requirements: samtools

@author: charles.hefer@gmail.com
@version 0.1
"""
import sys, os
import optparse
from socket import gethostname
from multiprocessing import Pool

def stop_err( msg ):
    sys.stderr.write( "%s\n" % msg )
    sys.exit()
 
def index_bam(bamfile):
    """
    Index the bam file
    """
    try: open("%s.bai" % bamfile).close()
    except:
		cmd = "samtools index %s" % (bamfile)
		os.system(cmd)
    
def __main__():
	#Parse Command Line
	parser = optparse.OptionParser()
	parser.add_option("-i", "--input", default=None, dest="input", 
                      help="The input location file")
	parser.add_option("-t", "--threads", default=4, dest="threads", 
                      help="The number of threads to use")
	(options, args) = parser.parse_args()
    
    #read the location file
	samples = [s.rstrip() for s in open(options.input, "r")]
        
    #this can be run in parallel
	pool = Pool(processes=int(options.threads))
	pool.map(index_bam, samples)
    
if __name__=="__main__": 
    __main__()